package com.zhuoan.im.webapp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhuoan.im.webapp.common.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * BaseController
 *
 * @author weixiang.wu
 * @date 2018 -04-01 13:16
 */
public class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 分页查询默认第一页
     */
    protected static final Integer PAGE_DEFAULT = 1;
    /**
     * 分页查询默认数量
     */
    protected static final Integer LIMIT_DEFAULT = 10;

    /**
     * The com.zhuoan.constant IPV4_LOCAL.
     */
    private static final String IPV4_LOCAL = "127.0.0.1";
    /**
     * The com.zhuoan.constant IPV6_LOCAL.
     */
    private static final String IPV6_LOCAL = "0:0:0:0:0:0:0:1";
    /**
     * The com.zhuoan.constant IP_UNKNOWN.
     */
    private static final String IP_UNKNOWN = "unknown";
    private static final String S = "\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>";

    /**
     * Gets page limit.
     *
     * @return the page limit
     */
    public int getPageLimit() {
        return LIMIT_DEFAULT;
    }


    /**
     * Gets the ip addr. 获取访问者真实IP地址
     *
     * @param request the request
     * @return the ip addr
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (ip.equals(IPV4_LOCAL) || ip.equals(IPV6_LOCAL)) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    logger.error("未知主机异常:", e);
                }
                if (inet != null) {
                    ip = inet.getHostAddress();
                }
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (StringUtils.isNotBlank(ip) && ip.contains(",")) { // "***.***.***.***".length()
            ip = ip.substring(0, ip.indexOf(','));
        }
        return ip;
    }


    /**
     * Gets ip.
     *
     * @return the ip
     */
    public static String getIp() {
        String ip = null;
        try {
            String chinaz = "http://ip.chinaz.com/?nitmdw=xbnj02";
            StringBuilder builder = new StringBuilder();
            String temp;
            HttpURLConnection urlConnection = (HttpURLConnection) new URL(chinaz).openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
            while ((temp = reader.readLine()) != null) {
                builder.append(temp).append("\n");
            }
            reader.close();

            Pattern p = Pattern.compile(S);
            Matcher m = p.matcher(builder.toString());
            if (m.find()) {
                String ipStr = m.group(1);
                ip = ipStr;
            }
        } catch (IOException e) {
            logger.error("", e);
        }
        return ip;
    }

    /**
     * Object to json string.
     *
     * @param <T> the type parameter
     * @param t   the t
     * @return the string
     */
    protected <T> String objectToJson(T t) {
        try {
            String response = JSONObject.toJSONString(t);
            logger.info("接口响应的数据response=[" + response + "]");
            return response;
        } catch (Exception e) {
            logger.info("接口返回数据转为json格式错误:", e);
            return null;
        }
    }
}
